﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    [DynamicApiController]
    public class EnterpriseController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public EnterpriseController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 企业列表
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PostList()
        {
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端-获取审核人
        /// </summary>
        /// <param name="eid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShenheren([FromForm] long eid)
        {
            //JArray data = new();
            string shenherens = await db.Queryable<Enterprise>().Where(e => e.Id == eid).Select(e => e.ExamineEpid).SingleAsync();
            List<Employee> employees = new();
            if (!string.IsNullOrEmpty(shenherens)) {
                employees = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{shenherens}')").OrderBy($"FIND_IN_SET(id, '{shenherens}')").ToListAsync();
                //string[] shenherenarr = shenherens.Split(",");
                //if (shenherenarr.Length > 0)
                //{

                //    foreach (var shenheren in shenherenarr)
                //    {
                //        Employee employee = await db.Queryable<Employee>().Where(ep => ep.Id == long.Parse(shenheren)).SingleAsync();
                //        JObject jo_employee = JObject.FromObject(employee);
                //        jo_employee.Add("shstatus", "");
                //        jo_employee.Add("comments", new JArray());
                //        data.Add(jo_employee);
                //    }
                //}
            }
            
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = employees,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端获取员工所在企业列表，第一条为默认企业
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public async Task<IActionResult> PostListbyepid([FromForm] long id)
        {
            long default_eid = await db.Queryable<Employee>().Where(ep => ep.Id == id).Select(ep => ep.DefaultEid).SingleAsync();
            // 企业列表
            JArray ja_enterprises = new();
            // 查询用户所在的企业并记录昵称
            List<EmployeeEnterprise> employee_enterprises = await db.Queryable<EmployeeEnterprise>().Where(ee => ee.Epid == id).ToListAsync();
            if (employee_enterprises?.Count > 0)
            {
                // 循环对应企业，获取企业信息
                foreach (var ee in employee_enterprises)
                {
                    Enterprise enterprise = await db.Queryable<Enterprise>().Where(e => e.Id == ee.Eid).FirstAsync();
                    JObject jo_enterprise = JObject.FromObject(enterprise);
                    jo_enterprise.Add("user_nickname", ee.NickName);
                    if (default_eid == ee.Id)
                    {
                        // 把默认企业放到第一个
                        ja_enterprises.Insert(0, jo_enterprise);
                    }
                    else
                    {
                        ja_enterprises.Add(jo_enterprise);
                    }
                }
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = ja_enterprises,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端-获取企业详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long id)
        {
            Enterprise enterprise = await db.Queryable<Enterprise>().Where(e => e.Id == id).SingleAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = enterprise,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 设置消息通知时间
        /// </summary>
        /// <param name="id"></param>
        /// <param name="notice"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSetnotice([FromForm] long id, [FromForm] int notice) {
            await db.Updateable<Enterprise>().SetColumns(e => e.Notice == notice).Where(e => e.Id == id).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 定义流程
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="examine_person"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostExaminePerson([FromForm] long eid, [FromForm] string examine_person)
        {
            await db.Updateable<Enterprise>().SetColumns(e => e.ExamineEpid == examine_person).Where(e => e.Id == eid).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        public async Task<IActionResult> PostUpdate([FromForm] Enterprise enterprise)
        {
            await db.Updateable<Enterprise>(enterprise).IgnoreColumns(e => e.ExamineEpid).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = enterprise,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
